package com.gwlc.system.config.aop;


import com.gwlc.common.annotation.PermissionAnnotation;
import com.gwlc.common.base.BaseAop;
import com.gwlc.common.config.LuckyConfig;
import com.gwlc.common.constant.system.user.UserStateConstant;
import com.gwlc.common.constant.system.user.UserTypeConstant;
import com.gwlc.common.exception.user.*;
import com.gwlc.common.util.TokenTool;
import com.gwlc.system.domain.UserDO;
import com.gwlc.system.domain.dto.UserPermissionDTO;
import com.gwlc.system.service.IUserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * <p>SeventhEpic-com.gwlc.system.config.aop-PermissionVerifyAop</p>
 * <p>Description:  </p>
 * <p>Copyright: Copyright (c) 2021</p>
 * <p>Company: hanchunit@163.com</p>
 *
 * @author hanchun
 * @version 1.0
 * @date 2021/8/21
 */
@Component
@Order(2)
@Aspect
public class PermissionVerifyAop extends BaseAop {

    Boolean verify = LuckyConfig.getVerify();
    @Autowired
    private IUserService userService;

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.gwlc.common.annotation.PermissionAnnotation)")
    public void permissionAop() {
    }

    /**
     * 权限环绕通知
     *
     * @param point 提供对连接点可用状态和有关它的静态信息的反射访问
     */
    @Before("permissionAop()")
    @ResponseBody
    public void isAccessMethod(JoinPoint point) {
        if (verify != null && !verify) {
            return;
        }

        //获取方法上接口
        MethodSignature signature = (MethodSignature) point.getSignature();

        PermissionAnnotation permissionAnnotation = signature.getMethod().getDeclaredAnnotation(PermissionAnnotation.class);
        //获取权限注解的值
        String[] permissionTags = permissionAnnotation.value();
//
//        System.out.println("****************************************");
//        System.out.println("需要的权限" + Arrays.toString(permissionTags));
//        System.out.println("****************************************");
        //获取用户令牌
        String token = getToken();

        if (token == null || "".equals(token)) {
            throw new NotLoginException();
        }
        //获取令牌超时时间
        Long outTime = null;
        try {
            outTime = (Long) (TokenTool.decodeTokenMap(token)).get("outTime");
        } catch (Exception e) {
            throw new NotLoginException();
        }

        if (verifyOutTime(outTime)) {
            throw new TokenOutTimeException();
        }

        UserDO user = userService.getUserByToken(token);
        if (user == null || user.getUserId() == null || user.getUserId() <= 0 || user.getUserToken().isEmpty()) {
            throw new NotTokenException();
        }
        if (!user.getUserStatus().equals(UserStateConstant.USER_STATE_NORMAL)) {
            throw new UserStateException();
        }


        if (user.getUserType().equals(UserTypeConstant.USER_TYPE_ROOT)) {
            return;
        }

        if (permissionTags.length <= 0) {
            return;
        }

        //获取当前用户的权限
        UserPermissionDTO userPermission = userService.getUserPermission(user);

        Map<String, String> userPermissionMap = userPermission.getPermissions();
        System.out.println("****************************************");
        System.out.println("用户的权限" + userPermissionMap);
        System.out.println("****************************************");
        if (userPermissionMap != null && !userPermissionMap.isEmpty()) {
            int flag = 0;

            for (String permissionTag : permissionTags) {

                for (String item : userPermissionMap.values()) {
                    if (permissionTag.equals(item)) {
                        flag++;
                        break;
                    }
                }
            }
            if (flag >= permissionTags.length) {
                return;
            } else {

                throw new NotPermissionException();
            }

        }
        throw new NotPermissionException();
    }



}
